// pages/personal/Information/Information.js
let http = require('../../../utils/api.js');
let domain = require('../../../utils/api.js');
import {
    login,
    myHttps
} from '../../../utils/util.js';
import {
    myHttpss
} from '../../../utils/json.js';
import {
    uploadHttp
} from '../../../utils/upload.js'; //上传图片
const date = new Date()
const years = []
const months = []
const days = []

for (let i = 1600; i <= date.getFullYear(); i++) {
    years.push(i)
}

for (let i = 1; i <= 12; i++) {
    months.push(i)
}

for (let i = 1; i <= 31; i++) {
    days.push(i)
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        birthdays: '',
        years: years,
        year: date.getFullYear(),
        months: months,
        month: 2,
        days: days,
        day: 2,
        value: [9999, 1, 1],
        birthday: false,
        show: false, //性别弹框
        avtarShow: false, //头像弹框
        userId: '', //userId
        userInfo: '', //个人信息
        nick_name:'',//用户昵称
        country:'',//城市
        sex: '', //性别
        avatar: '', //头像
        hiddenLoading: false,
        domain:'',//ip
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // console.log(options)
        this.setData({
            userId: options.userId,
            domain: domain.domain
        })
        this.GetInfo()
    },
    /**
    * 生命周期函数--监听页面显示
    */
    onShow: function () {
        this.GetInfo()
    },
    // 获取用户信息接口 
    GetInfo() {
        this.setData({
            hiddenLoading: false
        })
        var url = http.api.userInfo + this.data.userId;
        myHttps({
            url: url,
            method: "GET",
        }).then(res => {
            // console.log(res.data)
            if (res.code == 1) {
                // console.log(res.data.gender)
                if (res.data.gender == 0) {
                    this.setData({
                        sex: '女'
                    })
                } else if (res.data.gender == 1) {
                    this.setData({
                        sex: '男'
                    })
                }
                
                if (res.data.birthday != null) {//把从后台获取得时间戳格式话 渲染页面
                    var date = new Date(res.data.birthday)
                    var birthdaytime = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
                    // console.log(birthdaytime)
                    birthdaytime = birthdaytime.split('/')
                    
                    var birthdayyear = birthdaytime[0]
                    var birthdaymonth = birthdaytime[1]
                    var birthdayday = birthdaytime[2]

                    this.setData({
                        year: birthdayyear,
                        month: birthdaymonth,
                        day: birthdayday,
                    })
                }
                this.setData({
                    userInfo: res.data,
                    nick_name: res.data.nick_name,
                    country: res.data.country,
                    avatar: res.data.avatar,
                    hiddenLoading: true
                })
            }
        }).catch(err => {})
    },
    // 将生日格式话
    crtTimeFtt(val) {
        if (val != null) {
            var date = new Date(val)
            return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
        }
    },
    bindChange: function(e) {
        const val = e.detail.value
        this.setData({
            year: this.data.years[val[0]],
            month: this.data.months[val[1]],
            day: this.data.days[val[2]]
        })

    },
    // 点生日的时候显示
    gobirthday() {
        this.setData({
            birthday: true
        })
    },
    // 点击完成 弹框消失
    finish() {
        this.setData({
            birthday: false
        })
        let d = Date.parse(this.data.year + '/' + this.data.month + '/' + this.data.day)
        // let d = new Date(this.data.year + '-' + this.data.month + '-' + this.data.day)
        // console.log(d)
        // let t = d.getTime();//把时间转化成时间戳传给后台
        // console.log(Number(t))
        this.editorInfos(d)
    },
    // 更新用户信息接口 性别
    editorInfo(val) {
        var that = this
        let url = http.api.editorInfo + this.data.userId;
        let obj = this.data.userInfo;
        if (val == '女') {
            val = '0'
            obj.gender = val
        } else {
            val = '1'
            obj.gender = val
        }
        myHttpss({
            url: url,
            method: "PUT",
            data: obj
        }).then(res => {
            if (res.code == 1) {}
        }).catch(err => {})
    },
    // 更新用户信息接口 生日
    editorInfos(val) {
        var that = this
        let url = http.api.editorInfo + this.data.userId;
        let obj = this.data.userInfo;
        // console.log(val)
        obj.birthday = val
        // console.log(obj)
        myHttpss({
            url: url,
            method: "PUT",
            data: obj
        }).then(res => {
            if (res.code == 1) {
            }
        }).catch(err => {})
    },
    // 选择性别弹框
    chooseSex() {
        this.setData({
            show: true
        })
    },
    // 点击男
    nan(e) {
        // console.log(e.currentTarget.dataset.sex)
        this.setData({
            sex: '男'
        })
        this.editorInfo(e.currentTarget.dataset.sex)
    },
    // 点击女
    nv(e) {
        // console.log(e.currentTarget.dataset.sex)
        this.setData({
            sex: '女'
        })
        this.editorInfo(e.currentTarget.dataset.sex)
    },
    // 选择性别弹窗关闭
    cancel() {
        this.setData({
            show: false
        });
    },
    
    // 调用微信的相册相机功能
    chooseimage() {
        var that = this;
        wx.chooseImage({
            count: 1, // 默认9 
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有 
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有 
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
                const tempFilePaths = res.tempFilePaths
                wx.uploadFile({
                    // url: domain.domain, //仅为示例，非真实的接口地址
                    url: 'https://www.digitwonder.com/biz/auth/upload',
                    filePath: tempFilePaths[0],
                    name: 'file',
                    header: {
                        'content-type': 'multipart/form-data',
                        'Authorization': wx.getStorageSync('Authorization'),
                    },
                    formData: {
                        user: 'test'
                    },
                    success(res) {
                        // console.log(JSON.parse(res.data).data)
                        let imgAvatar = JSON.parse(res.data).data
                        // let imgAvatar = res.data
                        // 成功之后 更新个人信息
                        let url = http.api.editorInfo + that.data.userId;
                        let obj = that.data.userInfo;
                        obj.avatar = 'https://www.digitwonder.com' + imgAvatar
                        that.setData({
                            avatar: obj.avatar 
                        })
                        console.log(obj)
                        console.log(wx.getStorageSync('Authorization'))
                        myHttpss({
                            url: url,
                            method: "PUT",
                            data: obj
                        }).then(res => {
                            if (res.code == 1) {
                                wx.showToast({
                                    title: '上传头像成功',
                                    icon: 'success',
                                    image: '',
                                    duration: 0,
                                    mask: true,
                                    success: function(res) {},
                                    fail: function(res) {},
                                    complete: function(res) {},
                                })
                            }else {
                                wx.showToast({
                                    title: '上传头像失败,请重新上传',
                                    icon: 'none',
                                    image: '',
                                    duration: 0,
                                    mask: true,
                                    success: function (res) { },
                                    fail: function (res) { },
                                    complete: function (res) { },
                                })
                            }
                        }).catch(err => {
                            wx.showToast({
                                title: '网络错误',
                                image: '',
                                duration: 0,
                                mask: true,
                                success: function (res) { },
                                fail: function (res) { },
                                complete: function (res) { },
                            })
                        })
                    }
                })
            }
        })
    },
    // 修改昵称
    nickName() {
        wx.navigateTo({
            url: '../editorNick/editorNick',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    // 修改简介
    introduce() {
        wx.navigateTo({
            url: '../editorIntroduce/editorIntroduce',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    // 选择城市
    choosecity() {
        wx.navigateTo({
            url: '../city/city',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },

})